<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Check, Camera, Upload } from "@element-plus/icons-vue"
import request, { SERVER_BASE_URL } from "@/utils/request.js"
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const emit = defineEmits(["update"])

// 检查登录状态
const checkLoginStatus = () => {
  const userInfo = JSON.parse(localStorage.getItem('user'))
  if (!userInfo) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return false
  }
  return true
}

// 初始化用户数据
const initialUser = ref(null)
const user = ref({
  confirmPassword: '' // 新增确认密码字段
})

// 初始化用户信息
const initUserInfo = () => {
  if (!checkLoginStatus()) return

  initialUser.value = JSON.parse(localStorage.getItem('user') || '{}')
  initialUser.value.password = ''
  user.value = {
    ...JSON.parse(JSON.stringify(initialUser.value)),
    confirmPassword: ''
  }
  
  // 同步Pinia状态
  userStore.setUser(initialUser.value)
}

// 头像上传相关
const avatarDialogVisible = ref(false)
const avatarUrl = ref('')
const fileList = ref([])  

// 加载完成后刷新头像
const refreshAvatar = () => {
  // 只有在有头像URL的情况下刷新
  if (user.value.avatar) {
    setTimeout(() => {
      const imgElement = document.querySelector('.user-avatar img')
      if (imgElement) {
        imgElement.src = getAvatarUrl(user.value.avatar)
      }
    }, 500) // 稍微延迟确保DOM已更新
  }
}

// 在加载完成后初始化数据和刷新头像
onMounted(() => {
  initUserInfo()
  refreshAvatar()
})

// 头像上传前的钩子
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt5M = file.size / 1024 / 1024 < 5 // 调整为5MB

  if (!isJPG && !isPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('头像大小不能超过 5MB!')
    return false
  }
  return true
}

// 处理头像变更
const handleAvatarChange = (uploadFile) => {
  fileList.value = [uploadFile]
  avatarUrl.value = URL.createObjectURL(uploadFile.raw)
}

// 打开头像上传对话框
const handleavatar = () => {
  if (!checkLoginStatus()) return
  avatarDialogVisible.value = true
  fileList.value = []  // 清空文件列表
}

// 取消头像上传
const cancelAvatarUpload = () => {
  avatarDialogVisible.value = false
  avatarUrl.value = ''
  fileList.value = []
}

// 提交头像上传
const submitAvatarUpload = async () => {
  if (!checkLoginStatus()) return
  
  if (!fileList.value || fileList.value.length === 0) {
    ElMessage.warning('请先选择一张图片')
    return
  }
  
  try {
    // 创建FormData对象用于文件上传
    const formData = new FormData()
    formData.append('file', fileList.value[0].raw)
    formData.append('username', user.value.username)
    
    // 调用上传接口
    const res = await request.post('/upload/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (res.code === 200) {
      // 完整的头像URL路径
      const fullAvatarUrl = res.data
      
      // 确保URL是完整的
      const absoluteUrl = fullAvatarUrl.startsWith('http') 
        ? fullAvatarUrl 
        : SERVER_BASE_URL + fullAvatarUrl
      
      // 更新用户对象的头像URL
      user.value.avatar = absoluteUrl
      
      // 更新到数据库（调用用户头像更新接口）
      try {
        const updateRes = await request.put('/user/updateAvatar', {
          username: user.value.username,
          avatar: fullAvatarUrl
        })
        
        if (updateRes.code === 200) {
          // 更新本地存储和Pinia状态
          localStorage.setItem('user', JSON.stringify(user.value))
          initialUser.value = JSON.parse(JSON.stringify(user.value))
          userStore.setUser(user.value)
          
          // 刷新头像
          refreshAvatar()
          
          emit('update')
          ElMessage.success('头像上传成功')
          avatarDialogVisible.value = false
          // 清空上传状态
          avatarUrl.value = ''
          fileList.value = []
        } else {
          ElMessage.error(updateRes.message || '头像信息更新失败')
        }
      } catch (updateError) {
        console.error('头像信息更新错误:', updateError)
        ElMessage.error('头像信息更新失败，请稍后再试')
      }
    } else {
      ElMessage.error(res.message || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传错误:', error)
    ElMessage.error('头像上传失败，请稍后再试')
  }
}

// 保存用户信息
const handleSave = async () => {
  if (!checkLoginStatus()) return
  
  // 添加密码校验
  if (user.value.password && user.value.password !== user.value.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  try {
    // 确保version字段存在，如果不确定则从后端获取最新值
    if (user.value.version === undefined) {
      try {
        const userResponse = await request.get(`/user/selectByID?id=${user.value.id}`)
        if (userResponse.code === 200 && userResponse.data) {
          user.value.version = userResponse.data.version
        } else {
          ElMessage.error('获取用户信息失败，无法更新')
          return
        }
      } catch (error) {
        console.error('获取用户version失败:', error)
        ElMessage.error('获取用户信息失败，请重试')
        return
      }
    }
    
    // 发送更新请求，确保包含version字段
    let response = await request.put('/update', user.value)
    if (response.code === 200){
      // 更新version值
      user.value.version = (user.value.version || 0) + 1
      
      // 更新本地存储和Pinia状态
      localStorage.setItem('user', JSON.stringify(user.value))
      initialUser.value = JSON.parse(JSON.stringify(user.value))
      userStore.setUser(user.value)
      
      emit('update')
      ElMessage.success('资料更新成功')
    } else {
      // 获取最新用户数据并刷新表单
      try {
        const userResponse = await request.get(`/user/selectByID?id=${user.value.id}`)
        if (userResponse.code === 200 && userResponse.data) {
          user.value = userResponse.data
          user.value.confirmPassword = ''
          initialUser.value = JSON.parse(JSON.stringify(user.value))
          localStorage.setItem('user', JSON.stringify(user.value))
          userStore.setUser(user.value)
        }
      } catch (error) {
        console.error('获取最新用户数据失败:', error)
      }
      
      ElMessage.error(response.message || '保存失败，数据可能已被其他操作修改')
    }
  } catch (error) {
    console.error('更新用户信息错误:', error)
    user.value = JSON.parse(JSON.stringify(initialUser.value)) // 重置表单
    ElMessage.error('请求失败，已恢复原始数据')
  }
}

//处理头像图片url，添加时间戳避免缓存
const getAvatarUrl = (url) => {
  if (!url) return '';
  
  // 确保有服务器地址前缀
  let fullUrl = url;
  
  // 如果是相对路径，添加服务器地址前缀
  if (url.startsWith('/uploads/') || url.startsWith('/static/')) {
    // 避免重复添加SERVER_BASE_URL
    if (!url.includes('http://') && !url.includes('https://')) {
      fullUrl = SERVER_BASE_URL + url;
    }
  }
  
  // 添加时间戳
  const timestamp = Date.now();
  const result = fullUrl.includes('?') 
    ? `${fullUrl.split('?')[0]}?t=${timestamp}` 
    : `${fullUrl}?t=${timestamp}`;

  console.log('处理后的头像URL:', result);
  return result;
}
</script>

<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <div class="profile-header">
        <h2>个人资料</h2>
        <el-button
          :icon="Check"
          type="primary" 
          @click="handleSave"
          class="save-btn"
        >
          保存修改
        </el-button>
      </div>
      
      <el-form label-width="100px" class="profile-form">
        <el-row :gutter="40">
          <!-- 左侧头像区域 -->
          <el-col :xs="24" :sm="8" :md="6">
            <el-form-item label=" ">
              <div class="avatar-wrapper">
                <el-avatar 
                  :size="120" 
                  :src="getAvatarUrl(user.avatar)"
                  @click="handleavatar"
                  class="user-avatar"
                />
                <el-icon class="avatar-edit-icon">
                  <Camera />
                </el-icon>
              </div>
            </el-form-item>
          </el-col>

          <!-- 右侧信息区域 -->
          <el-col :xs="24" :sm="16" :md="18">
            <!-- 添加账号显示 -->
            <el-form-item label="账号" class="form-item-custom">
              <el-input 
                v-model="user.username" 
                placeholder="账号"
                disabled
                clearable
              />
            </el-form-item>

            <el-form-item label="昵称" class="form-item-custom">
              <el-input
                  v-model="user.nickname"
                  placeholder="请输入昵称"
                  clearable
              />
            </el-form-item>
            
            <el-form-item label="密码" class="form-item-custom">
              <el-input
                  v-model="user.password"
                  placeholder="请输入密码"
                  show-password
                  clearable
              />
            </el-form-item>
            
            <el-form-item label="确认密码" class="form-item-custom">
              <el-input
                  v-model="user.confirmPassword"
                  placeholder="请再次输入密码"
                  show-password
                  clearable
              />
            </el-form-item>
            
            <el-form-item label="邮箱" class="form-item-custom">
              <el-input 
                v-model="user.email"
                placeholder="请输入邮箱"
                type="email"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="个人简介" class="form-item-custom">
              <el-input 
                v-model="user.description" 
                type="textarea" 
                :rows="6"
                resize="none"
                placeholder="介绍一下自己吧"
                show-word-limit
                maxlength="200"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    
    <!-- 头像上传对话框 -->
    <el-dialog
      v-model="avatarDialogVisible"
      title="上传头像"
      width="400px"
      class="avatar-dialog"
    >
      <div class="avatar-upload-container">
        <!-- 头像预览 -->
        <div class="avatar-preview">
          <el-avatar
            :size="150"
            :src="avatarUrl || getAvatarUrl(user.avatar)"
            class="preview-avatar"
          >
            <el-icon><Camera /></el-icon>
          </el-avatar>
        </div>
        
        <!-- 上传控件 -->
        <el-upload
          class="avatar-uploader"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleAvatarChange"
          :before-upload="beforeAvatarUpload"
          :limit="1"
          :key="avatarDialogVisible + '_' + (fileList.length > 0 ? Date.now() : '')"
          accept="image/jpeg,image/png"
        >
          <el-button type="primary" :icon="Upload">选择图片</el-button>
          <template #tip>
            <div class="el-upload__tip">
              只能上传一张 JPG/PNG 文件，且不超过 5MB
            </div>
          </template>
        </el-upload>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAvatarUpload">取消</el-button>
          <el-button type="primary" @click="submitAvatarUpload">确认上传</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.profile-container {
  padding: 30px;
  height: 80%;
  max-height: calc(100vh - 100px);
}

.profile-card {
  max-width: 1000px;
  margin: 0 auto;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  height: 100%;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color);
}

.profile-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.avatar-wrapper {
  position: relative;
  display: inline-block;
  cursor: pointer;
  transition: transform 0.3s;
}

.avatar-wrapper:hover {
  transform: scale(1.05);
}

.user-avatar {
  border: 2px solid var(--el-color-primary);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar-edit-icon {
  position: absolute;
  right: 5px;
  bottom: 5px;
  padding: 5px;
  background: var(--el-color-primary);
  color: white;
  border-radius: 50%;
  font-size: 16px;
}

.form-item-custom :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.save-btn {
  padding: 12px 24px;
  font-size: 16px;
  transition: all 0.3s;
}

.save-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(32, 160, 255, 0.3);
}

/* 头像上传样式 */
.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.avatar-preview {
  padding: 20px;
  display: flex;
  justify-content: center;
}

.preview-avatar {
  border: 2px dashed var(--el-border-color);
  background-color: #f5f7fa;
}

.avatar-uploader {
  width: 100%;
  text-align: center;
}

.avatar-dialog :deep(.el-dialog__header) {
  padding-bottom: 15px;
  margin-bottom: 15px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.avatar-dialog :deep(.el-dialog__footer) {
  padding-top: 15px;
  margin-top: 15px;
  border-top: 1px solid var(--el-border-color-light);
}

/* 隐藏滚动条但保持滚动功能 */
:deep(.el-scrollbar__bar) {
  display: none;
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}

.el-upload__tip {
  color: #909399;
  margin-top: 10px;
  text-align: center;
}
</style>